$(function () {
  var $oInputAddFiles = $("#input-add-files")
  var $oFilesList = $(".files-list")
  var $nameInput = $(".item.name input"),
    $ageInput = $(".item.age input"),
    $phoneInput = $(".item.phone input"),
    $emailInput = $(".item.email input"),
    $weixinInput = $(".item.weixin input"),
    $pictureInput = $(".item.picture input"),
    $selectImgBtn = $(".item.picture .img-wrap"),
    $selectImgInput = $selectImgBtn.prev("input[type=file]"),
    $explainTextarea = $(".item.explain textarea"),
    $sexRadio = $(".item.sex input[type=radio]"),
    $objectCheckbox = $(".item.object input[type=checkbox]"),
    $workTimeSelect = $(".work-time .selectpicker")

  $.ajax({
    url: ports.verifyToken,
    success: function (res) {
      console.log("验证token是否有效", res)
      if (res.status == 200) {
        if (!res.data) {
          window.location.replace(globalUrl.login + "?returnUrl=" + encodeURIComponent(window.location.href))
        }
      }
    },
  })
  $.ajax({
    url: ports.getLessonConfig,
    success: function (res) {
      console.log("获取我要讲课配置", res)
      if (res.status == 200) {
        $(".publish-notice").html(res.data.notice)
        $(".upload-explain").html(res.data.note)
        var maxFileCount = res.data.maxCount
        var maxFileSize = res.data.maxSize
        var allowFiles = []

        function showErrorSign(el) {
          if (!el.next(".error-sign").length) {
            el.after('<span class="error-sign">' + el.data("errorSign") + "</span>")
          }
        }

        function hideErrorSign(el) {
          el.next(".error-sign").remove()
        }
        function testAllowFiles() {
          if (allowFiles.length) {
            hideErrorSign($(".btn-select-file"))
            return true
          } else {
            showErrorSign($(".btn-select-file"))
            return false
          }
        }

        function testValEmpty(el, str, maxLength) {
          var val = str || el.val().trim()
          var max = maxLength || 200
          if (!val || val.length > max) {
            showErrorSign(el)
            return false
          } else {
            hideErrorSign(el)
            return true
          }
        }

        $selectImgBtn.click(function () {
          $selectImgInput.click()
        })
        $selectImgInput.change(function (e) {
          var file = this
          var filemaxsize = 1024 * 1000000 //5M
          var target = $(e.target)
          var Size = target[0].files[0].size / 1024
          if (!file.files[0].type.match(/^image\/.*jpg|jpeg|png$/)) {
            utils.showToast({
              title: "请选择.jpg、.png格式的图片",
              type: "warning",
            })
            return false
          }
          if (Size > filemaxsize) {
            utils.showToast({
              title: "图片过大，请重新选择",
              type: "warning",
            })
            return false
          }
          var reader = new FileReader()
          if (file) {
            reader.readAsDataURL(file.files[0])
          }
          // 捕获 转换完毕
          reader.onload = function (e) {
            // 转换后的base64就在e.target.result里面,直接放到img标签的src属性即可
            $selectImgBtn.children("img").prop("src", e.target.result)
            hideErrorSign($(file))
          }
        })

        function get_filemd5sum(ofile, callback) {
          var file = ofile
          var tmp_md5
          var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
            // file = this.files[0],
            chunkSize = 8097152, // Read in chunks of 2MB
            chunks = Math.ceil(file.size / chunkSize),
            currentChunk = 0,
            spark = new SparkMD5.ArrayBuffer(),
            fileReader = new FileReader()

          function frOnload(e) {
            // console.log('read chunk nr', currentChunk + 1, 'of', chunks);
            spark.append(e.target.result) // Append array buffer
            currentChunk++
            var md5_progress = Math.floor((currentChunk / chunks) * 100)

            console.log(file.name + "  正在处理，请稍等," + "已完成" + md5_progress + "%")
            // var handler_info = document.getElementById("handler_info");
            // var progressbar = document.getElementsByClassName("progressbar")[0];
            // handler_info.innerHTML=file.name + "  正在处理，请稍等," + "已完成" + md5_progress + "%"
            // progressbar.value =md5_progress;
            if (currentChunk < chunks) {
              loadNext()
            } else {
              tmp_md5 = spark.end()
              // console.log(tmp_md5);
              callback(tmp_md5)
              // handler_info.innerHTML = file.name + "的MD5值是：" + tmp_md5;
            }
          }

          fileReader.onload = frOnload

          fileReader.onerror = function () {
            console.warn("文件解析错误")
          }

          function loadNext() {
            var start = currentChunk * chunkSize,
              end = start + chunkSize >= file.size ? file.size : start + chunkSize
            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
          }

          loadNext()
        }

        $(".btn-select-file").click(function () {
          $("#input-add-files").click()
        })

        $oInputAddFiles.on("input", function (e) {
          if ($(this).val()) {
            var $that = $(this)
            var file = this
            var fileList = file.files
            var filemaxsize = 1024 * maxFileSize //5M

            var notAllowFile = 0

            $.each(fileList, function (i, item) {
              if (allowFiles.length < maxFileCount) {
                if (item.name.match(/\.doc|docx|ppt|pptx|xls|xlsx|pdf$/) && item.size / 1024 <= filemaxsize) {
                  ;(function (i) {
                    get_filemd5sum(item, function (md5) {
                      var pass = true
                      $oFilesList.children().each(function (j, item) {
                        // console.log($(this).data('md5'),md5,$(this).data('md5')==md5)
                        if ($(this).data("md5") == md5) {
                          pass = false
                          notAllowFile += 1
                        }
                      })
                      if (!pass) return false
                      if (allowFiles.length < maxFileCount) {
                        $oFilesList.append(
                          "<li data-md5=" +
                            md5 +
                            ">\n" +
                            '                   <i class="iconfont icon-fujian2"></i>\n' +
                            '                   <span class="file-name" title=' +
                            item.name +
                            ">" +
                            item.name +
                            "</span>\n" +
                            '                   <span class="size">（' +
                            item.size / 1000 +
                            "KB）</span>" +
                            '                   <span class="btn-delete">删除</span>\n' +
                            "               </li>"
                        )
                        $oFilesList
                          .find(".btn-delete")
                          .unbind("click")
                          .click(function () {
                            allowFiles.splice($(this).parent().index(), 1)
                            testAllowFiles()
                            // console.log(allowFiles)
                            if (allowFiles.length === 0) {
                              $(".btn-select-file span").text("添加")
                            }
                            $(this).parent().remove()
                          })
                        // allowFileFromData.append('files', item);
                        allowFiles.push(item)
                        testAllowFiles()
                      } else {
                        notAllowFile += 1
                      }
                    })
                  })(i)
                } else {
                  notAllowFile += 1
                }
              } else {
                utils.showToast({
                  title: "最多只能添加" + maxFileCount + "个文件，已自动过滤多余文件",
                  type: "warning",
                })
              }
            })

            setTimeout(function () {
              console.log(allowFiles, notAllowFile)
              if (notAllowFile == fileList.length) {
                utils.showToast({
                  title: "没有符合规则的文件，请重新选择",
                  type: "warning",
                })
                return false
              } else if (notAllowFile) {
                utils.showToast({
                  title: "已过滤不合规则或重复的文件",
                })
              }
              $that.val("")
              if (allowFiles.length) {
                $(".btn-select-file span").text("继续添加")
              }
            }, 500)
          }
        })

        $nameInput.on("input", function () {
          testValEmpty($(this), "", 16)
        })
        $workTimeSelect.change(function () {
          // $(this).children('[value=0]').remove();
          hideErrorSign($(this))
          $(this).prev().find("[data-original-index=0]").remove()
        })
        $ageInput.on("input", function () {
          var ageReg = /^[1-9][0-9]$/
          if (!ageReg.test($(this).val())) {
            showErrorSign($(this))
          } else {
            hideErrorSign($(this))
          }
        })
        $phoneInput.on("input", function () {
          testValEmpty($(this), "", 16)
          if (!$phoneInput.val().trim() && !$weixinInput.val().trim() && !$emailInput.val().trim()) {
            $(".item.contact .sub").addClass("error")
          } else {
            $(".item.contact .sub").removeClass("error")
          }
        })
        $weixinInput.on("input", function () {
          testValEmpty($(this), "", 20)
          if (!$phoneInput.val().trim() && !$weixinInput.val().trim() && !$emailInput.val().trim()) {
            $(".item.contact .sub").addClass("error")
          } else {
            $(".item.contact .sub").removeClass("error")
          }
        })
        $emailInput.on("input", function () {
          if ($(this).val().trim() && !utils.testEmail($(this).val().trim())) {
            showErrorSign($(this))
          } else {
            hideErrorSign($(this))
          }
          if (!$phoneInput.val().trim() && !$weixinInput.val().trim() && !$emailInput.val().trim()) {
            $(".item.contact .sub").addClass("error")
          } else {
            $(".item.contact .sub").removeClass("error")
          }
        })
        $explainTextarea.on("input", function () {
          var val = $(this).val().trim()
          if (val) {
            if (val.length > 300) {
              $(this).parent().addClass("error")
            } else {
              $(this).parent().removeClass("error")
            }
            $(this)
              .nextAll(".input-limit")
              .html(val.length + "/" + 300)
            testValEmpty($(this), "", 300)
          } else {
            showErrorSign($(this))
          }
        })

        function submitContribution(callback, callCatch) {
          var pass = true

          if (!testValEmpty($nameInput, "", 16)) {
            pass = false
          }

          if ($workTimeSelect.val() == 0) {
            pass = false
            showErrorSign($workTimeSelect)
          }

          var ageReg = /^[1-9][0-9]$/
          if (!ageReg.test($ageInput.val())) {
            pass = false
            showErrorSign($ageInput)
          }

          if (
            !$selectImgInput.prop("files").length ||
            !$selectImgInput.prop("files")[0].type.match(/^image\/.*jpg|jpeg|png$/)
          ) {
            pass = false
            showErrorSign($selectImgInput)
          }

          if (!testValEmpty($explainTextarea, "", 300)) {
            pass = false
          }

          if (!testAllowFiles()) {
            pass = false
            showErrorSign($(".btn-select-file"))
          }

          if ($objectCheckbox.filter(":checked").length === 0) {
            pass = false
            $(".object .error-sign").css("display", "block")
          }

          var emailPass = utils.testEmail($emailInput.val().trim())
          var weixinPass = $weixinInput.val().trim().length >= 1 && $weixinInput.val().trim().length <= 20
          var phonePass = $phoneInput.val().trim().length >= 1 && $weixinInput.val().trim().length <= 16
          /*if(!emailPass&&!weixinPass&&!phonePass){
                        $('.item.contact .sub').addClass('error');
                        pass = false;
                    }*/
          if ($phoneInput.val().trim() && !phonePass) {
            pass = false
          }
          if ($weixinInput.val().trim() && !weixinPass) {
            pass = false
          }
          if ($emailInput.val().trim() && !emailPass) {
            pass = false
          }
          if (!$phoneInput.val().trim() && !$weixinInput.val().trim() && !$emailInput.val().trim()) {
            $(".item.contact .sub").addClass("error")
            pass = false
          }

          if (pass) {
            var allowFileFromData = new FormData()
            allowFileFromData.set("name", $nameInput.val())
            allowFileFromData.set("tel", $phoneInput.val())
            allowFileFromData.set("email", $emailInput.val())
            allowFileFromData.set("weixin", $weixinInput.val())
            allowFileFromData.set("spanId", $workTimeSelect.val())
            allowFileFromData.set("age", $ageInput.val())
            allowFileFromData.set("gender", $sexRadio.filter(":checked").val())
            allowFileFromData.set("image", $selectImgInput.prop("files")[0])
            allowFileFromData.set("resume", $explainTextarea.val())
            $.each(allowFiles, function (i, item) {
              allowFileFromData.append("files", item)
            })
            $objectCheckbox.filter(":checked").each(function (i, item) {
              allowFileFromData.append("lessonObjects", $(item).val())
            })
            axios({
              method: "post",
              url: ports.saveLesson,
              data: allowFileFromData,
              contentType: "multipart/form-data;",
              responseType: "json",
              headers: {
                Authorization: utils.cookieUtils.getCookie("token"),
              },
            })
              .then(function (res) {
                console.log("提交我要讲课", res)
                if (res.data.status == 200) {
                  callback()
                } else {
                  callCatch()
                  utils.showToast({
                    title: res.data.data,
                    type: "warning",
                  })
                }
              })
              .catch(function (err) {
                callCatch(err)
              })
          } else {
            callCatch()
          }
        }
        $(".btn.save").click(function () {
          var that = this
          $(that).text("提交中")
          $(that).attr("disabled", "disabled")
          submitContribution(
            function () {
              utils.showModal({
                content: "小编已收到您的信息，<br>感谢您对政府采购信息网的支持！",
                success: function (res) {
                  if (res.confirm) {
                    window.location.href = "/"
                  }
                },
              })
            },
            function () {
              $(that).removeAttr("disabled")
              $(that).text("立即提交")
            }
          )
        })
        $(".btn.again").click(function () {
          submitContribution(function () {
            $contributionTitleInput.val("")
            allowFiles = []
            $(window).scrollTop(0)
          })
        })
      }
    },
  })
  $.ajax({
    url: ports.listLessonSpan,
    success: function (res) {
      console.log("获取我要讲课政府采购从业时间", res)
      $workTimeSelect.append('<option value="0">请选择</option>')
      $.each(res.data, function (i, item) {
        $workTimeSelect.append("<option value=" + item.id + ">" + item.spanName + "</option>")
      })
      $workTimeSelect.selectpicker({})
    },
  })
  $.ajax({
    url: ports.listLessonObject,
    success: function (res) {
      console.log("获取我要讲课授课对象", res)
      $.each(res.data, function (i, item) {
        $(".form-wrap .object .value").append(
          '<div class="checkbox"><input id=' +
            "checkbox-object-" +
            i +
            ' name="checkbox" type="checkbox" value=' +
            item.id +
            "><label for=" +
            "checkbox-object-" +
            i +
            ' class="checkbox-label">' +
            item.objectName +
            "</label></div>"
        )
      })
      $objectCheckbox = $(".item.object input[type=checkbox]")
      $objectCheckbox.change(function () {
        if ($objectCheckbox.filter(":checked").length) {
          $(".object .error-sign").css("display", "none")
        } else {
          $(".object .error-sign").css("display", "block")
        }
      })
    },
  })
})
